package com.example.heraclitoapp;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.example.heraclitoapp.HeraclitoActivity;
import com.example.heraclitoapp.R;
import com.example.heraclitoapp.MainActivity;

import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;

public class LoginDialog extends Dialog {
	
	private static final String NAMESPACE = "http://ws.org.br/";
	private static final String METHOD_NAME = "performLogin2";
	private static final String URL = "http://obaa.unisinos.br:80/WSServer/WSAgent?wsdl";
	private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
	
	SoapObject request = new SoapObject(NAMESPACE,
			METHOD_NAME);

	public LoginDialog(final Context context) {
		super(context);
		setContentView(R.layout.login); //this.setC
		setTitle(context.getString(R.string.login));
		
		final Button login_ok = (Button) findViewById(R.id.login_ok);
		final Button login_cancelar = (Button) findViewById(R.id.login_cancelar);

		final EditText login_caixa = (EditText) findViewById(R.id.login_caixa);
		final EditText login_password = (EditText) findViewById(R.id.login_password);

		final ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar1);
		final TextSwitcher mensagemLogin = (TextSwitcher) findViewById(R.id.mensagemLogin);

		//final TextView mensagemLogadoComo = (TextView) findViewById(R.id.logadoComo);

		login_ok.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				MainActivity.usuario = login_caixa.getText().toString();
				MainActivity.senha = login_password.getText().toString();

				Animation in = AnimationUtils.loadAnimation(context,
						android.R.anim.fade_in);
				Animation out = AnimationUtils.loadAnimation(context,
						android.R.anim.fade_out);

				mensagemLogin.setInAnimation(in);
				mensagemLogin.setOutAnimation(out);

				if (mensagemLogin.getChildCount() > 0) {
					mensagemLogin.removeAllViews();
				}

				mensagemLogin.addView(new TextView(context));
				mensagemLogin.addView(new TextView(context));

				new Login(context, progress,
						mensagemLogin).execute(
						MainActivity.usuario, MainActivity.senha);
			}
		});

		login_cancelar.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				dismiss();
			}
		});

		//show();
	}
	
	public class Login extends AsyncTask<String, String, String> {
		ProgressBar progressBar;
		Context mContext;
		//Dialog loginDialog;
		TextSwitcher mensagemLogin;
		TextView mensagemUsuarioLogado;
		String mensagemUsuarioUser;
		Button mButtonLogin;

		public Login(Context mContext, ProgressBar mProgressBar,
				TextSwitcher mensagemLogin) {
			this.mContext = mContext;
			this.progressBar = mProgressBar;
		//	this.loginDialog = loginDialog;
			this.mensagemLogin = mensagemLogin;
			this.mButtonLogin = mButtonLogin;
			//this.mensagemUsuarioLogado = mensagemUsuarioLogado;
		}

		@Override
		protected void onPreExecute() {

			AlphaAnimation fadeIn;
			fadeIn = new AlphaAnimation(0, 1); // fade out animation from 1
												// (fully visible) to 0
												// (transparent)
			fadeIn.setDuration(150); // set duration in mill seconds
			// fadeIn.setFillAfter(true);
			progressBar.startAnimation(fadeIn);

			TextView loginTexto = (TextView) mensagemLogin.getChildAt(0);
			loginTexto.setTextColor(Color.BLACK);

			TextView loginTexto2 = (TextView) mensagemLogin.getChildAt(1);
			loginTexto2.setTextColor(Color.BLACK);

			progressBar.setVisibility(View.VISIBLE);
			mensagemLogin.setText(mContext.getString(
					R.string.autenticando)
					+ "...");
		}

		@Override
		protected String doInBackground(String... params) {
			mensagemUsuarioUser = params[0];

			request.addProperty("userId", params[0]);
			request.addProperty("password", params[1]);
			request.addProperty("localHost", "");

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);

			HttpTransportSE transport = new HttpTransportSE(URL);
			String resposta = new String();

			try {
				transport.call(SOAP_ACTION, envelope);

				Object response = envelope.getResponse();

				if (response != null) {
					if (response instanceof SoapPrimitive) {
						SoapPrimitive respostaAgente = (SoapPrimitive) response;
						resposta = respostaAgente.toString();
						return resposta;
					} else if (response instanceof SoapObject) {
						// SoapObject answerAgent = (SoapObject) response;

						resposta = mContext.getString(
								R.string.login_invalido);
						/**
						 * for (int i = 0; i < answerAgent.getPropertyCount();
						 * i++) { resposta +=
						 * answerAgent.getProperty(i).toString(); }
						 **/
						
					}
					// mensagemLogin.setCurrentText(resposta);
					// Toast.makeText(getBaseContext(), response.toString(),
					// Toast.LENGTH_LONG).show();
				}

			} catch (Exception e) {
				//Log.e("fjsdffsdkfdf", resposta);
			}
			
			publishProgress();
			// Toast.makeText(mContext, resposta, Toast.LENGTH_LONG).show();
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// espera();

			// progressBar.setVisibility(View.GONE);
			if (result != null) {

				// Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
				if (!result.contains("logado")) {
					if (result.contains("Erro")) {
						result = mContext.getString(R.string.workaround_login);
					}
					mensagemLogin.setText(result);
				}

				AlphaAnimation fadeOut;
				fadeOut = new AlphaAnimation(1, 0); // fade out animation from 1
													// (fully visible) to 0
													// (transparent)
				fadeOut.setDuration(3100); // set duration in mill seconds
				fadeOut.setFillAfter(true);
				progressBar.startAnimation(fadeOut);

				if (result.contains("Erro") || result.contains("Digite")) {
					return;
				} else {
					MainActivity.logado = 1;
					espera();
					MainActivity.btn_login.setText("Logoff");
				
					
					// loginDialog.dismiss();
				}

			} else {
				mensagemLogin.setText(mContext.getString(
						R.string.impossivel_login));
				AlphaAnimation fadeOut;
				fadeOut = new AlphaAnimation(1, 0); // fade out animation from 1
													// (fully visible) to 0
													// (transparent)
				fadeOut.setDuration(1600); // set duration in mill seconds
				fadeOut.setFillAfter(true);
				progressBar.startAnimation(fadeOut);
				// Toast.makeText(mContext, "não foi possível fazer login",
				// Toast.LENGTH_LONG).show();
			}

			// Toast.makeText(mContext, result, Toast.LENGTH_SHORT).show();
		}

		@Override
		protected void onProgressUpdate(String... values) {

			// progressBar.setProgress(0x1);
			// Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
		}

		public void espera() {
			final Handler handler = new Handler();

			Timer t = new Timer();
			t.schedule(new TimerTask() {
				public void run() {
					handler.post(new Runnable() {
						public void run() {
							dismiss();
							MainActivity.logadoComo.setText(mensagemUsuarioUser);
							//mensagemUsuarioLogado.setText(o);
						}
					});
				}
			}, 2500);

		}

	}

	
}
